<template>
  <div class="contianer">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-form :model="tableData" :rules="rules" ref="tableData" label-width="100px" class="demo-ruleForm">
          <table>
            <tr>
              <td colspan="2">
                <el-form-item label="文章标题" prop="title">
                  <el-input v-model="tableData.title" placeholder="请输入标题"></el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <el-form-item label="正文内容" prop="content">
                  <quill-editor class="editor" v-model="tableData.content" ref="content" :options="editorOption"
                    @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)">
                  </quill-editor>
                </el-form-item>
              </td>

            </tr>
            <tr>
              <td colspan="2">
                <el-form-item label="文章标签">
                  <div class="block">
                    <el-cascader placeholder="点击添加标签" :options="options" :props="{ multiple: true }" v-model="tagList"
                      :show-all-levels="false" id="tagList" clearable filterable></el-cascader>
                  </div>
                  <!-- <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false"
                    @close="handleClose(tag)">
                    {{ tag }}
                  </el-tag>
                  <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
                    @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button> -->
                </el-form-item>
              </td>

            </tr>
            <tr>

              <td style="width: 25%;">
                <el-form-item label="文章封面" id="coverForm">
                  <el-upload action="api/util/uploadImg" list-type="picture-card" :auto-upload="true"
                    :on-change="handleExceed" :file-list="fileList" :limit="1" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload" name="imgFile">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                      <img class="el-upload-list__item-thumbnail" :src="tableData.fileUid">
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <!-- <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                          <i class="el-icon-download"></i>
                        </span> -->
                        <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
              </td>
              <td style="width: 75%;">
                <el-form-item label="文章摘要" prop="title" id="summary">
                  <el-input v-model="tableData.summary" placeholder="文章摘要" type="textarea" id="summaryInput"></el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <el-form-item label="是否原创">
                  <!-- <el-radio-group v-model="tableData.isOriginal">
                    <el-radio :label="1">原创</el-radio>
                    <el-radio :label="2">转载</el-radio>
                  </el-radio-group> -->
                  <el-radio-group v-model="tableData.isOriginal">
                    <el-radio-button label="原创"></el-radio-button>
                    <el-radio-button label="转载"></el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <div class="formButton">
                  <el-form-item style="float: right;">
                    <el-button type="danger" @click="resetForm('tableData')" round>重置内容</el-button>
                    <el-button type="success" @click="lookForm()" round>预览</el-button>
                    <el-button type="primary" @click="submitForm()" id="submitDiv" round>立即发布</el-button>
                  </el-form-item>
                </div>
              </td>
            </tr>

          </table>


        </el-form>


      </el-col>
      <el-col :span="8">
        <div class="left">
        </div>
      </el-col>
    </el-row>


  </div>
</template>

<script>
export default {
  name: "addArticle",
  data() {
    return {
      tableData: {
        id: '',//id标识
        title: '',//博客标题
        summary: '',//博客简介
        content: '',//博客内容
        tagUid: '',//标签uid
        clickCount: 0,//博客点击数
        collectCount: 0,//博客收藏数
        fileUid: '',//标题图片uid
        createdTime: '',//创建时间
        modifiedTime: '',//更新时间
        isOriginal: "原创",//原创
        author: '',//作者
        articlesPart: '',//文章出处
        openComment: '',//是否开启评论
      },
      editorOption: {},
      uploadFiles: [],
      fileList: [],
      editForm: {
        chairImg: ""
      },//图片上传成功后返回的路径，用户回调函数


      //标签
      // dynamicTags: [],
      // inputVisible: false,
      // inputValue: '',

      tagList: [],
      
      options: [
        {
          value: '类型',
          label: '类型',
          children: [
            {
              value: '编程开发',
              label: '编程开发',
            },
            {
              value: '踩坑记录',
              label: '踩坑记录'
            },
            {
              value: '知识笔记',
              label: '知识笔记'
            },
            {
              value: '项目介绍',
              label: '项目介绍'
            },
            {
              value: '文章转载',
              label: '文章转载'
            },
            {
              value: '围群成长史',
              label: '围群成长史'
            }
          ]
        },
        {
          value: 'java',
          label: 'java',
          children: [
            {
              value: 'tomcat',
              label: 'tomcat'
            },
            {
              value: 'intellij-idea',
              label: 'intellij-idea'
            },
            {
              value: 'jvm',
              label: 'jvm'
            },
            {
              value: 'spring',
              label: 'spring'
            },
            {
              value: 'maven',
              label: 'maven'
            },
          ]
        },
        {
          value: '编程语言',
          label: '编程语言',
          children: [
            {
              value: 'java',
              label: 'java',
            },
            {
              value: 'python',
              label: 'python'
            },
            {
              value: 'php',
              label: 'php'
            },
            {
              value: 'c++',
              label: 'c++'
            },
            {
              value: 'javascript',
              label: 'javascript++'
            },
            {
              value: 'c语言',
              label: 'c语言'
            },
          ]
        },
      ],

      //封面属性
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,


      //表单规则
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],

      }
    };
  },
  created() {
  },
  methods: {

    //图片上传
    handleAvatarSuccess(res) {

      if (res.success) {
        this.tableData.fileUid = res.data.resPath
        this.$message({
          type: 'success',
          message: ""
        })
      } else {
        this.$message({
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      // 设置限定格式
      const img_mimetype = ['image/jpeg', 'image/jpg', 'image/png']
      const isJPG = img_mimetype.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error('上传头像只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
        return false;
      }
      return isJPG && isLt2M;
    },
    // 提交修改的表单数据
    // editChairmans() {
    //   const { data: rese } = this.$axios.post('api/blog/uploadimg', this.editForm);
    // },

    //封面方法
    handleRemove(file) {//移除图片

      this.$axios.post("api/util/deleteUploadImg", { oosImgPath: this.tableData.fileUid }).then((res) => {
        if (res.data.success) {
          this.fileList = [];
          if (this.fileList.length >= 1) {
            this.getstyle(".el-upload--picture-card").display = "none";
          } else {
            setTimeout(() => {
              this.getstyle(".el-upload--picture-card").display = "inline-block"
            }, 1150);
          }
          this.$message({ type: 'success' })
        } else {
          this.$message({ type: 'error' })
        }
      });

    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },




    getNowTime() {
      let now = new Date();
      let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
      let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
      let today = now.getDate(); //获取当前日(1-31)
      let hour = now.getHours(); //获取当前小时数(0-23)
      let minute = now.getMinutes(); //获取当前分钟数(0-59)
      let second = now.getSeconds(); //获取当前秒数(0-59)
      let nowTime = ''
      nowTime = year + '-' + (month) + '-' + (today) + ' ' + (hour) + ':' +
        (minute) + ':' + (second)
      return nowTime;
    },
    resetForm(formName) {
      this.$confirm('是否清空该文章编辑?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs[formName].resetFields();
        this.$message({
          type: 'success',
          message: '已清空'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
      // if(confirm("是否清空该文章编辑？")){
      //   this.$refs[formName].resetFields();
      // }

    },



    // handleDownload(file) {
    //   console.log(file);
    // },
    getstyle(sname) {//从整个页面查找class为sname的页面
      for (var i = 0; i < document.styleSheets.length; i++) {
        var rules;
        if (document.styleSheets[i].cssRules) {
          rules = document.styleSheets[i].cssRules;
        } else {
          rules = document.styleSheets[i].rules;
        }
        for (var j = 0; j < rules.length; j++) {
          if (rules[j].selectorText == sname) {
            return rules[j].style;
          }
        }
      }
    },

    handleExceed(files, fileList) {
      this.fileList = fileList;
      if (this.fileList.length >= 1) {
        this.getstyle(".el-upload--picture-card").display = "none";
      } else {
        this.getstyle(".el-upload--picture-card").display = "inline-block";
      }

    },

    //事件
    addArticle() {
    },
    onEditorBlur() {
    },
    onEditorFocus() {//获得焦点事件
    },
    onEditorChange() {//内容改变事件
    },



    //传输图片添加
    // Vue.prototype.hostURL = 'http://localhost:8081/static/'




    imgUrlToBase64(url) {
      return new Promise((resolve, reject) => {
        if (!url) {
          reject('请传入url内容')
        }
        // 图片地址
        const image = new Image()
        // 设置跨域问题
        image.setAttribute('crossOrigin', 'anonymous')
        // 图片地址
        image.src = url
        image.onload = () => {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          canvas.width = image.width
          canvas.height = image.height
          ctx.drawImage(image, 0, 0, image.width, image.height)
          // 获取图片后缀
          const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase()
          // 转base64
          const dataUrl = canvas.toDataURL(`image/${ext}`)
          resolve(dataUrl || '')
        }
      })
    },



    getBase64(imgUrl) {
      return new Promise((resolve, reject) => {
        if (!imgUrl) {
          reject('请传入imgUrl内容')
        }
        if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(imgUrl)) {
          window.URL = window.URL || window.webkitURL
          var xhr = new XMLHttpRequest()
          xhr.open('get', imgUrl, true)
          xhr.responseType = 'blob'
          xhr.onload = function () {
            if (this.status == 200) {
              // 得到一个blob对象
              var blob = this.response
              const oFileReader = new FileReader()
              oFileReader.onloadend = function (e) {
                const base64 = e.target.result
                resolve(base64 || '')
              }
              oFileReader.readAsDataURL(blob)
            }
          }
          xhr.send()
        } else {
          // 非图片地址
          reject('非(png/jpe?g/gif/svg等)图片地址')
        }
      })
    },

    //预览
    lookForm() {
      //将信息缓存到浏览器里面
      console.log(this.tableData);
      this.tableData.createdTime = this.getNowTime();
      var arr = JSON.stringify(this.tableData)
      window.localStorage.setItem("formData", arr);



      //将封面信息传给预览界面fileList
      var fileList = JSON.stringify(this.fileList)
      window.localStorage.setItem("fileList", fileList);


      console.log(this.fileList);


      //标签组
      var tag = JSON.stringify(this.tagList);
      window.localStorage.setItem("tagList", tag)
      this.$router.push({
        name: 'previewArticle',
      });
    },

    //提交方法
    submitForm() {
      var tagArr = [];
      for(var i = 0;i<this.tagList.length;i++){
        tagArr[i] = this.tagList[i][1];
      }

      this.tableData.isOriginal = this.tableData.isOriginal == "原创"?"1":"0";
      console.log(this.tableData);
      this.$axios.post("api/blog/addArticle",{wqunBlog:this.tableData,tagArr:tagArr}).then((res) => {
        if(res.success){
          console.log(res);
        }
        
      });


    },
  },

}

</script>


<style scoped>
.contianer {
  min-width: 1270px;
}


.left {
  background-color: #cccccc;
  min-width: 100px;
  height: 1000px;
  padding: 10px;
  margin: 2%;
  margin-left: 12%;
}

#coverForm {
  display: inline-block;
  height: 150px;
  width: 25%;
}

#summary {
  display: inline-block;
  margin-left: 5%;
  width: 95%;
  height: 150px;
}

#summaryInput {
  height: 150px;
}

#tagList {
  min-width: 500px;
}

.formButton {
  bottom: 0px;
  min-width: 900px;

}
</style>


<style>
.ql-editor {
  min-height: 300px;
}


.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>